﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class AssemblyFileRule : ILRule<AssemblyFileHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        [ILInfo]
        public byte[] HashValue { get; }

        [ILInfo]
        public bool ContainsMetadata { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public AssemblyFileRule(
            string name,
            byte[] hashValue,
            bool containsMetadata)
            : base()
        {
            Name = name;
            HashValue = hashValue;
            ContainsMetadata = containsMetadata;
        }

        public AssemblyFileRule(MetadataReader reader, AssemblyFileHandle assemblyFileHandle)
            : base(reader)
        {
            AssemblyFile assemblyFile = reader.GetAssemblyFile(assemblyFileHandle);
            ContainsMetadata = assemblyFile.ContainsMetadata;
            HashValue = reader.GetBlobBytes(assemblyFile.HashValue);
            Name = reader.GetString(assemblyFile.Name);
            CustomAttributes = assemblyFile.GetCustomAttributes();
        }

        public override AssemblyFileHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddAssemblyFile(
                name: Name == null ? default : builder.GetOrAddString(Name),
                hashValue: HashValue == null ? default : builder.GetOrAddBlob(HashValue),
                containsMetadata: ContainsMetadata);
        }
    }
}